import os

from flask import Blueprint, render_template, session, request, jsonify, send_from_directory

from app.models import Order, House, OrderContract

order_bp = Blueprint('order_bp', __name__)


@order_bp.route('/orders/', methods=['GET'])
def orders():
    return render_template('orders.html')


@order_bp.route('/my_orders/', methods=['GET'])
def my_orders():
    data = []
    orders_data = Order.query.filter(Order.user_id == session['user_id']).all()
    for order in orders_data:
        data.append(order.to_dict())
    return jsonify({'code': 200, 'msg': '获取页面成功', 'orders': data})


# 客户订单页
@order_bp.route('/lorders/', methods=['GET'])
def lorders():
    return render_template('lorders.html')


@order_bp.route('/lorder/', methods=['GET'])
def lorder():
    hlist = House.query.filter(House.user_id == session['user_id'])
    hid_list = [house.id for house in hlist]

    # 根据房屋编号查找订单
    order_list = Order.query.filter(Order.house_id.in_(hid_list)).order_by(Order.id.desc()).all()

    # 构造结果并查找合同信息
    olist = []
    for order in order_list:
        order_dict = order.to_dict()  # 获取订单的字典表示

        # 查找合同信息
        contract = OrderContract.query.filter(OrderContract.order_id == order.id).first()
        if contract:
            order_dict['contract_path'] = contract.contract_path  # 将合同路径添加到订单字典中
        else:
            order_dict['contract_path'] = None  # 如果没有合同，添加一个None字段

        olist.append(order_dict)

    return jsonify({'code': 200, 'msg': '获取页面成功', 'orders': olist})


@order_bp.route('/pay/', methods=['POST'])
def pay_order():
    order_id = request.form.get('order_id')
    order = Order.query.filter_by(id=order_id).first()

    if order.status != 'WAIT_PAYMENT':
        return jsonify({'success': False, 'message': 'Order is not in a payable state.'})
    order.status = 'PAID'
    order.add_update()
    return jsonify({'success': True, 'message': 'Payment successful.'})


@order_bp.route('/lorders/', methods=['PUT'])
def my_lorders():
    status = request.form.get('status')

    order_id = request.form.get('order_id')
    order = Order.query.filter(Order.id == order_id).first()
    order.status = status
    order.add_update()

    return jsonify({'code': 200, 'msg': '修改接单状态成功'})


@order_bp.route('/upload_contract/', methods=['POST'])
def upload_contract():
    if 'contract' not in request.files:
        return jsonify({'success': False, 'message': '没有文件上传'}), 400

    file = request.files['contract']
    if file.filename == '':
        return jsonify({'success': False, 'message': '未选择文件'}), 400

    if file:
        order_id = request.form['order_id']
        filename = f'{order_id}-{file.filename}'
        file_path = os.path.join('static', 'files', filename)
        file.save(file_path)
        contract = OrderContract.query.filter(OrderContract.id == order_id).first()
        if contract:
            contract.contract_path = file_path
        else:
            contract = OrderContract(order_id=order_id, contract_path=file_path)
        contract.add_update()

        return jsonify({'success': True, 'message': '合同上传成功'}), 200

    return jsonify({'success': False, 'message': '文件类型不允许'}), 400


@order_bp.route('/download_contract/<int:order_id>', methods=['GET'])
def download_contract(order_id):
    # 查询合同路径
    contract = OrderContract.query.filter(OrderContract.order_id == order_id).first()

    if contract and contract.contract_path:
        # 获取合同文件的路径
        file_path = contract.contract_path
        name = file_path.split('/')[-1]
        file_path = file_path.replace(name, '')
        # 返回文件
        print(file_path)
        print(os.getcwd())
        return send_from_directory(directory=file_path, filename=name, as_attachment=True)
    return jsonify({'success': False, 'message': '合同不存在'}), 404
